<template>
  <el-input
    v-if="withFilter"
    v-model="filterText"
    :placeholder="placeholder"
    :suffix-icon="Search"
    class="filterInput"
  />
  <el-tree
    ref="TreeRef"
    :data="Props.data"
    node-key="id"
    :props="Props.props"
    :filter-node-method="filterNode"
    v-bind="attrs"
  >
    <!-- slot for customize node -->
    <!-- <template #default="{ node, data }">
      {{ node?.label }}
    </template> -->
    <template #default="{ node, data }">
      <slot :node="node" :data="data">
        <div class="nodeLine" v-tooltip-auto-show>
          <el-tooltip :content="node.label" placement="right">
            <div class="onelineOverflow w100">
              {{ node.label }}
            </div>
          </el-tooltip>
        </div>
      </slot>
    </template>
  </el-tree>
</template>

<script setup>
import { Search } from '@element-plus/icons-vue';
const TreeRef = ref();

const attrs = useAttrs();

const filterText = ref('');

watch(filterText, val => TreeRef.value?.filter(val), { immediate: false });

function clearFilterText() {
  filterText.value = '';
}

const Props = defineProps({
  data: {
    required: true,
    default: [],
  },
  props: {
    type: Object,
    default: () => ({
      label: 'label',
      children: 'children',
      disabled: 'disabled',
      isLeaf: 'isLeaf',
      class: 'class',
    }),
  },
  withFilter: {
    type: Boolean,
    default: false,
  },
  placeholder: {
    type: String,
    default: 'Filter keyword',
  },
});

function filterNode(value, node) {
  if (!value) return true;
  return node[Props.props?.label || 'label']?.toLowerCase()?.includes(value.toLowerCase());
}
defineExpose({ ref: TreeRef, clearFilterText });
</script>

<style scoped lang="scss">
.filterInput {
  margin-bottom: 10px;
}
.w100 {
  width: 100%;
}
.nodeLine {
  overflow: hidden;
}
</style>
